package com.hn.gege.core.conf;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.hn.gege.core.modules.sys.entity.DatabaseRecord;
import com.hn.gege.core.modules.sys.service.IDatabaseRecordService;
import com.hn.gege.core.util.SpringContextUtil;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
 
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
@SuppressWarnings({"unchecked", "rawtypes"})
public class MybatisInterceptor implements Interceptor {
 
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Class<MybatisInterceptor> mybatisInterceptorClass = MybatisInterceptor.class;

        try {
            // 获取xml中的一个select/update/insert/delete节点，是一条SQL语句
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            // 只拦截更新和删除
            if (mappedStatement.getSqlCommandType() != SqlCommandType.DELETE && mappedStatement.getSqlCommandType() != SqlCommandType.UPDATE) {
                return invocation.proceed();
            }

            Object parameter = null;
            if (invocation.getArgs().length > 1) {
                parameter = invocation.getArgs()[1];
            }
 
            // BoundSql就是封装myBatis最终产生的sql类
            BoundSql boundSql = mappedStatement.getBoundSql(parameter);
 
            // 获取节点的配置
            Configuration configuration = mappedStatement.getConfiguration();
            // 获取到最终的sql语句
            String sql = showSql(configuration, boundSql);
            // 表名
            String tableName = getTableName(sql, mappedStatement.getSqlCommandType());
            // 执行sql类型(insert,update,delete,select)
            String sqlType = mappedStatement.getSqlCommandType().name();
            // 获取where条件
            String[] sqlArr = sql.split("where");
            String where = "";
            if (sqlArr.length == 2) {
                where = sqlArr[1];
            }
            // 判断表名是否需要记录
            if (!isIgnoreTable(tableName)) {
                // 获取更改前先获取
                List<Map<String, Object>> obj = SpringContextUtil.getBean(IDatabaseRecordService.class).datas(tableName, where);
                String bacthNo = IdUtil.fastSimpleUUID();
                List<DatabaseRecord> databaseRecords = new ArrayList<>();
                obj.forEach(item -> {
                    DatabaseRecord dataRecord = new DatabaseRecord();
                    dataRecord.setBizId(item.get("id").toString());
                    dataRecord.setBatchNo(bacthNo);
                    dataRecord.setSqlTxt(sql);
                    dataRecord.setSqlType(sqlType);
                    dataRecord.setTableName(tableName);
                    dataRecord.setModifyData(JSON.toJSONString(item));
                    dataRecord.setCreateTime(LocalDateTime.now());
                    databaseRecords.add(dataRecord);
                });

                SpringContextUtil.getBean(IDatabaseRecordService.class).saveBatch(databaseRecords);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 执行完上面的任务后，不改变原有的sql执行过程
        return invocation.proceed();
    }
 
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
 
    @Override
    public void setProperties(Properties properties) {
 
    }


    // 进行？的替换
    public static String showSql(Configuration configuration, BoundSql boundSql) {
        // 获取参数
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        // sql语句中多个空格都用一个空格代替
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (CollUtil.isNotEmpty(parameterMappings) && parameterObject != null) {
            // 获取类型处理器注册器，类型处理器的功能是进行java类型和数据库类型的转换
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            // 如果根据parameterObject.getClass(）可以找到对应的类型，则替换
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?",
                    Matcher.quoteReplacement(getParameterValue(parameterObject)));
            } else {
                // MetaObject主要是封装了originalObject对象，提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?",
                            Matcher.quoteReplacement(getParameterValue(obj)));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        // 该分支是动态sql
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?",
                            Matcher.quoteReplacement(getParameterValue(obj)));
                    } else {
                        // 打印出缺失，提醒该参数缺失并防止错位
                        sql = sql.replaceFirst("\\?", "缺失");
                    }
                }
            }
        }
        return sql.toLowerCase();
    }

    /**
     * 获取表名
     * @param sql
     * @param type
     * @return
     */
    private static String getTableName(String sql, SqlCommandType type) {
        if (SqlCommandType.UPDATE == type) {
            return sql.substring(sql.indexOf("update") + 7, sql.indexOf("set")-1);
        } else if (SqlCommandType.DELETE == type) {
            return sql.substring(sql.indexOf("from") + 5, sql.indexOf("where")-1);
        }
        return "";
    }


    /**
     * 过滤掉不需要,保存变更记录的表
     * @param tableName
     * @return
     */
    private boolean isIgnoreTable(String tableName) {
        List<String> ignoreTableList = new ArrayList<>();
        ignoreTableList.add("sys_oper_log");

        if (ignoreTableList.contains(tableName)) {
            return true;
        }
        return false;
    }

    /**
     * 封装了一下sql语句，使得结果返回完整xml路径下的sql语句节点id + sql语句
     * @param configuration
     * @param boundSql
     * @param sqlId
     * @return
     */
    public static String getSql(Configuration configuration, BoundSql boundSql, String sqlId) {
        String sql = showSql(configuration, boundSql);
        StringBuilder str = new StringBuilder(100);
        str.append(sqlId);
        str.append(":");
        str.append(sql);
        return str.toString();
    }

    // 如果参数是String，则添加单引号， 如果是日期，则转换为时间格式器并加单引号； 对参数是null和不是null的情况作了处理
    private static String getParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT,
                DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(new Date()) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }
        }
        return value;
    }

}